package com.aspirecn.order.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.aspirecn.order.domain.ResponseMsg;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.aspirecn.order.common.RestApiConstants;
import com.aspirecn.order.domain.RequestMsg;
import com.aspirecn.order.domain.ResponseHead;
import com.aspirecn.order.domain.vo.QueryUserInfoByUserNameInVo;
import com.aspirecn.order.domain.vo.QueryUserInfoByUserNameOutVo;

/**
 * 不通过服务发现使用Hystrix访问内部或外部服务
 * @author chenyuanli
 */
@Service
public class UserServiceNoDiscoClient {
	private static final Logger LOG = LoggerFactory.getLogger(UserServiceNoDiscoClient.class);
	
    @Autowired
    RestTemplate restTemplate;

//    @Autowired
//    @LoadBalanced  如果要开启负载均衡，前提是接入注册服务
//    RestTemplate restTemplate;

    /**
     * @param msg
     * @return
     */
    @HystrixCommand(fallbackMethod = "error")//default timeout 1000ms
    public ResponseMsg<QueryUserInfoByUserNameOutVo> queryUserInfoByUserName(RequestMsg<QueryUserInfoByUserNameInVo> msg) {
    	HttpHeaders headers =new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity request=new HttpEntity(msg, headers);
        
        //范型response必须使用exchange
        return restTemplate.exchange("http://10.9.20.92:10801/user/queryUserInfoByUserName", 
    			HttpMethod.POST, 
    			request,  
    			new ParameterizedTypeReference<ResponseMsg<QueryUserInfoByUserNameOutVo>>() {}).getBody();
    }


    /**
     * @param msg
     * @return
     */
    @HystrixCommand(fallbackMethod = "error")
    public QueryUserInfoByUserNameOutVo queryUserInfoByUserNameForNoneGenerics(RequestMsg<QueryUserInfoByUserNameInVo> msg) {
    	
    	return restTemplate.postForObject("http://10.9.20.92:10801/user/queryUserInfoByUserName", 
							    			msg, 
							    			QueryUserInfoByUserNameOutVo.class);
    }

    /**
     * @param msg
     * @return
     */
    public ResponseMsg<QueryUserInfoByUserNameOutVo> error(RequestMsg<QueryUserInfoByUserNameInVo> msg) {
    	ResponseMsg<QueryUserInfoByUserNameOutVo> response = new ResponseMsg<QueryUserInfoByUserNameOutVo>();
    	ResponseHead head = new ResponseHead();
    	response.setHead(head);
    	head.setRespCode(RestApiConstants.RESPCODE_FAILED);
    	head.setRespStatus(RestApiConstants.RESPSTATUS_FAILED);
    	head.setRespDesc("User Service fallback");
        return response;
    }
    
}
